package com.dingpeikeji.quickdeer.mobile.service;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.modules.cupons.entity.CuponsInfo;
import com.dingpeikeji.quickdeer.core.modules.cupons.service.TCuponsService;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.core.modules.site.entity.TSitedtl;
import com.dingpeikeji.quickdeer.core.modules.site.service.TSitedtlService;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Office;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.core.modules.sys.service.OfficeService;
import com.dingpeikeji.quickdeer.modules.base.web.FSysController;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.ProRentOrders;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TCargotype;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TCargotypeForsale;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentproduct;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.FRentproductService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.RentproductOrderService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentgroupService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentproductService;
import com.dingpeikeji.quickdeer.utils.BackResult;
import com.dingpeikeji.quickdeer.utils.UUIDUtils;
import com.google.common.collect.Lists;

@Service
@Transactional(readOnly = true)
public class MobileAirRentService {
	@Autowired
	private TRentproductService tRentproductService;
	@Autowired
	private RentproductOrderService rentproductOrderService;
	@Autowired
	private FRentproductService rentproductService;
	@Autowired
	private TRentgroupService tRentgroupService;
	@Autowired
	private TSitedtlService tSitedtlService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private TCuponsService tCuponsService;
	@Autowired
	private OrderService orderService;

	//接送机查询
	public BackResult getAirList(CuponsInfo cuponsInfo,TRentproduct tRentproduct, HttpServletRequest request, 
			HttpServletResponse response, Model model,TCargotypeForsale cargotypeForsale)
					throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		//手机端传入日期格式 2000-01-01 06:00
		String fromdateStr = request.getParameter("fromdateStr");
		String[] arr = fromdateStr.split("\\s");//按空格切割
		tRentproduct.setFromdateStr(arr[0]);
		tRentproduct.setTime(arr[1]);
		// 如果发车日期为空或者小于当前日期，则设置成明天
		// 包车天数为空，1天-10天选择，默认1天
		tRentproduct.handleFromDate(model).handleDaysnum();
		String destSiteName = request.getParameter("destcity.sitename");//目的地
		String detailAddress = request.getParameter("aboardAddress");//详细地址
		//获取车型
		TCargotype cargotype = new TCargotype();
		String tstyle = request.getParameter("tstyle");
		cargotypeForsale.setCargotype(cargotype);
		cargotypeForsale.getCargotype().setTstyles(tstyle);
		//百度地图自动赋值城市名称,根据名称查询
		TSitedtl sitedtl = tSitedtlService.getDestCityByName(tRentproduct.getDestcity().getSitename());
		if (sitedtl!=null) {
			tRentproduct.setDestcity(sitedtl);//不匹配,重新赋值
			cargotypeForsale.setDepartcity(tRentproduct.getDepartcity());
			cargotypeForsale.setDestcity(tRentproduct.getDestcity());
		}else{
			tRentproduct.setDestcity(null);//查询不到目的地
			cargotypeForsale.setDepartcity(tRentproduct.getDepartcity());
			cargotypeForsale.setDestcity(tRentproduct.getDestcity());
		}
		//产品名称
		String productName = "";
		if (tRentproduct.getDestcity()!=null) {
			productName = tRentproduct.getDepartcity().getSitename()
					+"-"+tRentproduct.getDestcity().getSitename()+"("+tRentproduct.getTabType()+")";
		}else{
			productName = tRentproduct.getDepartcity().getSitename()
					+"-"+destSiteName+"("+tRentproduct.getTabType()+")";
		}
		tRentproduct.setProductname(productName);
		tRentproduct.setAboardAddress(detailAddress);
		String kms = tRentproduct.getMapkm();//地图测算的距离
		double distance = 0.0;
		int disLevel = 0;
		if (StringUtils.isNotEmpty(kms)) {
			if (kms.indexOf("公里")!=-1) {
				distance = Double.parseDouble(kms.substring(0, kms.indexOf("公里")));
				if (distance<=50&&distance>=0) {
					disLevel = 1;
				}else if (distance<=150&&distance>50) {
					disLevel = 2;
				}else if (distance<=275&&distance>150) {
					disLevel = 3;
				}else if (distance<=500&&distance>275) {
					disLevel = 4;
				}else {
					disLevel = 5;
				}
			}else{
				disLevel = 1;//距离太近,取不到公里数
			}
		}
		
		//根据出发地,目的地 查询所有车型
		Page<TCargotypeForsale> page = new Page<TCargotypeForsale>(request, response);
		page.setPageSize(Integer.parseInt(request.getParameter("pageSize")));
		page.setPageNo(Integer.parseInt(request.getParameter("pageNo")));
		cargotypeForsale.setPage(page);
		List<TCargotypeForsale> cargotypeList = rentproductService.findAirCargotypeList(cargotypeForsale);
		page.setList(cargotypeList);
		List<Office> officeList = null;
		//根据车型获取对应的车队
		if (cargotypeList.size()>0&&cargotypeList!=null) {
			for (TCargotypeForsale tc : cargotypeList) {
				double condition0 = ((tc.getCargotype().getNudePrice()/2.00+100)+
						(tc.getCargotype().getOilcost()+tc.getCargotype().getRoadmodules())*distance*2);
				double condition1 = (tc.getCargotype().getNudePrice()+
						(tc.getCargotype().getOilcost()+tc.getCargotype().getRoadmodules())*distance*2);
				double condition2 = (((tc.getCargotype().getNudePrice()+300)*(distance/500+1))+
						(tc.getCargotype().getOilcost()+tc.getCargotype().getRoadmodules())*distance*2);
				Set<Double> priceSet = new TreeSet<Double>();
				List<Double> priceList = new ArrayList<Double>();
				tc.setDepartcity(tRentproduct.getDepartcity());
				tc.setDestcity(tRentproduct.getDestcity());
				tc.setDisLevel(disLevel);//距离等级
				officeList = rentproductService.findAirProductByType(tc);
				if (officeList.size()>0&&officeList!=null) {
					for (Office office : officeList) {
						if (distance<=50&&distance>=0) {
							office.setSuitrtnprice(Math.ceil(condition0*office.getFactor()));
						}else if(distance<=500&&distance>50) {
							office.setSuitrtnprice(Math.ceil(condition1*office.getFactor()));
						}else {
							office.setSuitrtnprice(Math.ceil(condition2*office.getFactor()));
						}
						}
				}
				tc.setOfficeList(officeList);
				//取最低价
				for (Office office : officeList) {
					priceSet.add(office.getSuitrtnprice());
				}
				for (Double double1 : priceSet) {
					priceList.add(double1);
				}
				if (priceList.size()>0) {
					tc.setLowestAirPrice(priceList.get(0));
				}
			}
		}else{
			return BackResult.build("400", "未查询到数据");
		}
		
		map.put("rentproductList", cargotypeList);
		map.put("totalCount", page.getCount());
		map.put("tRentproduct", tRentproduct);
		return BackResult.ok(map);
	}
	public BackResult submitAirRentOrder(CuponsInfo cuponsInfo,TOrders orders, Model model,
			HttpServletRequest request,TRentproduct tRentproduct) throws Exception {
		String id = officeService.findIdByAbbr(request.getParameter("office.name"));
		tRentproduct.getOffice().setId(id);
		Map<String, Object> map = new HashMap<String, Object>();
		//接收出发地,目的地
		String departcitySitename = request.getParameter("departcity.sitename");
		String destcitySitename = request.getParameter("destcity.sitename");
		orders.setDepartcity(departcitySitename);
		orders.setDestcity(destcitySitename);
		orders.setBookingdays(1);//接送机默认一天
		orders.setOrderuserid(request.getParameter("userid"));
		orders.setCargotypeid(tRentproduct.getCargotype().getCargotypeid());
		orders.getOffice().setId(id);
		//设置realscheid,
		orders.setRealscheid(System.currentTimeMillis()+"");
		//设置价格
		orders.setDueamount(request.getParameter("totalPrice"));
		// 消息集合
		List<String> messages = Lists.newArrayList(); // 消息
		//处理时间
		orders.setDepartdateStr(request.getParameter("fromdateStr"));
		if (messages.isEmpty()) {
			ProRentOrders pro = null;
			try {
				pro = rentproductOrderService.genOrder(orders);
				@SuppressWarnings("unused")
				boolean success = pro.success();
				if (pro.success()) { // 如果成功生成订单，跳到支付方式选择页面
					Integer orderid = pro.getOrderid();
					orders.setOrderid(orderid+"");
					map.put("orders", orders);
					//改变优惠券使用状态
					if(cuponsInfo.getCuponsId()!=null&&cuponsInfo.getCuponsId().length()>0){
						CuponsInfo a = tCuponsService.getCuponsByRecordId(cuponsInfo.getCuponsId());
						if(Double.parseDouble(orders.getDueamount())+Double.parseDouble(cuponsInfo.getMoney())<Double.parseDouble(a.getMinPrice())){
							return BackResult.build("400", "提交失败");
				    	}
						orderService.updateOrderUseCupon(orders.getOrderid());
						cuponsInfo.setOrderId(orders.getOrderid());
						cuponsInfo.setUseTime(new Date());
						tCuponsService.useCupon(cuponsInfo);
					}
					return BackResult.ok(map);
				}
				messages.add(pro.getReturnmsg());
			} catch (Exception e) {
				messages.add(e.getMessage());
			}
		}
		return BackResult.build("400", messages.get(0));
	}
}
